package util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public final class CollectionRandomUtil {
	public static final ThreadLocalRandom random = ThreadLocalRandom.current();

	/**
	 * 从给定列表中随机选取count个组成新列表返回，注意返回的元素非空
	 *
	 * @param list  待选取列表
	 * @param count 要选择的元素个数
	 * @param <T>   列表元素类型
	 */
	public static <T> List<T> randomOrder(List<T> list, int count) {
		if (count >= list.size()) return list;

		ArrayList<T> res = new ArrayList<>();
		int size = list.size();
		for (int i = 0; i < count; i++) {
			int d = random.nextInt(size);
			T t = selectOneNoNull(list, d);
			if (t != null)
				res.add(t);
		}
		return res;
	}

	/**
	 * 选择一个元素返回并将列表该索引处置为null
	 *
	 * @param list 目标列表
	 * @param i    索引
	 * @param <T>  列表元素
	 */
	private static <T> T selectOneNoNull(List<T> list, int i) {
		T res = null;
		int p;
		for (int j = 0; j < list.size(); j++) {
			p = (j + i) % list.size();
			if (list.get(p) != null) {
				res = list.get(p);
				list.set(p, null);
				break;
			}
		}
		return res;
	}
}
